using System;
using System.Collections.Generic;
using DomainModel;
using Repository.Abstract;
using Services.Abstract;
using Services.Concrete.Exceptions;

namespace Services.Concrete
{
    public abstract class Service<T> : IService<T> where T : EntityBase
    {
        private readonly IRepository<T> _repository;

        protected Service(IRepository<T> repository)
        {
            _repository = repository;
        }

        public virtual void Save(T entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            if (_repository.GetById(entity.Id) != null)
                throw new CUDEntityException("Entity with such Id already exists.");

            _repository.SaveOrUpdate(entity);
        }

        public virtual void Update(T entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            if (_repository.GetById(entity.Id) == null)
                throw new CUDEntityException("Entity with such Id does not exists.");

            _repository.SaveOrUpdate(entity);
        }

        public virtual void Delete(T entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            if (_repository.GetById(entity.Id) == null)
                throw new CUDEntityException("Entity with such Id does not exists.");

            _repository.Delete(entity);
        }

        public virtual T GetById(long id)
        {
            return id <= 0 ? null : _repository.GetById(id);
        }

        public virtual List<T> GetAll()
        {
            return (List<T>)_repository.GetAll();
        }
    }
}